package com.js.rtu.fragment.forth;

import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.view.View;
import android.widget.TextView;

import androidx.appcompat.app.AlertDialog;

import com.js.rtu.MainActivity;
import com.js.rtu.R;
import com.js.rtu.base.BaseFragment;
import com.js.rtu.event.IniFileChooseEvent;
import com.js.rtu.event.StartBrotherEvent;
import com.js.rtu.util.SPUtils;
import com.nbsp.materialfilepicker.MaterialFilePicker;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.io.File;
import java.util.regex.Pattern;

import butterknife.BindView;
import butterknife.OnClick;


/**
 * Created by zwz on 2020/4/22.
 */
public class SettingsFragment extends BaseFragment {


    @BindView(R.id.tv_version)
    TextView tvVersion;

    @BindView(R.id.tv_time)
    TextView tvTime;
    @BindView(R.id.tv_timeout)
    TextView tvTimeout;
    @BindView(R.id.tv_path)
    TextView tvPath;


    public static SettingsFragment newInstance() {
        Bundle args = new Bundle();
        SettingsFragment fragment = new SettingsFragment();
        fragment.setArguments(args);
        return fragment;
    }


    @Override
    protected int getLayoutId() {
        return R.layout.fragment_tab_forth_settingst;
    }

    @Override
    protected void initView() {
        EventBus.getDefault().register(this);
        tvVersion.setText(getVersionName(_mActivity));
        tvTime.setText(String.format("%s", SPUtils.get(_mActivity, "time_beat", 20)));

        tvTimeout.setText(String.format("%s", SPUtils.get(_mActivity, "time_out", 15)));

        tvPath.setText(String.format("%s", SPUtils.get(_mActivity, "path", "默认")));


    }

    //版本名
    public String getVersionName(Context context) {
        return getPackageInfo(context).versionName;
    }


    private static PackageInfo getPackageInfo(Context context) {
        PackageInfo pi = null;
        try {
            PackageManager pm = context.getPackageManager();
            pi = pm.getPackageInfo(context.getPackageName(),
                    PackageManager.GET_CONFIGURATIONS);
            return pi;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return pi;
    }


    @OnClick({R.id.ll_ini, R.id.ll_time, R.id.ll_timeout, R.id.tv_path, R.id.tv_setting, R.id.tv_bd})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.ll_ini:
                // Show dialog whenever you want by
                new MaterialFilePicker()
                        .withActivity(_mActivity)
                        .withCloseMenu(true)
                        .withHiddenFiles(true)
                        .withFilter(Pattern.compile(".*\\.ini$"))
                        .withFilterDirectories(false)
                        .withTitle("请选择ini配置文件")
                        .withRequestCode(1111)
                        .start();
                break;
            case R.id.ll_time:
                setTimeBeat(tvTime, "心跳间隔(s)");
                break;
            case R.id.ll_timeout:
                setTimeOut(tvTimeout, "超时时间(s)");
                break;
            case R.id.tv_path:
                toastShow(tvPath.getText().toString());
                break;
            case R.id.tv_setting:
                EventBus.getDefault().post(new StartBrotherEvent(AIFragment.newInstance()));
                break;
            case R.id.tv_bd:
                EventBus.getDefault().post(new StartBrotherEvent(BDFragment.newInstance()));
                break;
        }
    }


    @Subscribe(threadMode = ThreadMode.MAIN)
    public void receiveFilePath(IniFileChooseEvent event) {
        tvPath.setText(event.path);
        SPUtils.put(_mActivity, "path", event.path);
        toastShow("切换成功，5S后将重新启动");
        new Thread(() -> {
            try {
                Thread.sleep(5000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            Intent intent = new Intent(_mActivity, MainActivity.class);
            intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            _mActivity.startActivity(intent);
            android.os.Process.killProcess(android.os.Process.myPid());
        }).start();

    }

    private void setTimeBeat(final TextView tv, String title) {
        final String[] strs = {"5", "6", "7", "8", "9", "10", "15", "20", "25", "30",};//心跳时间
        new AlertDialog.Builder(_mActivity).setTitle(title).setItems(strs, new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialogInterface, int pos) {
                tv.setText(strs[pos]);
                dialogInterface.dismiss();
                SPUtils.put(_mActivity, "time_beat", Integer.parseInt(strs[pos]));

            }
        }).show();
    }

    private void setTimeOut(final TextView tv, String title) {
        final String[] strs = {"15", "16", "17", "18", "19", "20", "25", "30", "35", "40",};//超时时间
        new AlertDialog.Builder(_mActivity).setTitle(title).setItems(strs, new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialogInterface, int pos) {
                tv.setText(strs[pos]);
                dialogInterface.dismiss();
                SPUtils.put(_mActivity, "time_out", Integer.parseInt(strs[pos]));

            }
        }).show();
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }
}
